﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;

using Newtonsoft.Json;

/*
 * JSON数据操作帮助类
 * Newtonsoft控件
 * 2010年12月8日
 * William
 */

namespace Utility
{
    public class ListTree
    {
        public ListTree()
        {
            list = null;
            child = null;
            brother = null;
        }

        public List<Hashtable> list;
        public ListTree father;
        public ListTree child;
        public ListTree brother;
    }

    public class JSONHelper
    {
        public static JSONHelper Instance = new JSONHelper();

        private JSONHelper()
        { }

        public string JavaScriptConvertMachion(object value)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(value);
        }

        public T JavaScriptDeserializationMachion<T>(string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
        }

        public DataTable PagationCloneDataTable(DataTable dt, int pageIndex, int pageSize)
        {

            int startIndex = 0;
            if (dt == null || dt.Rows.Count <= 0)
            {
                return dt;
            }

            if (pageIndex == -1 || pageSize == -1)
            {
                pageIndex = 0;
                pageSize = 500;
            }

            startIndex = pageIndex * pageSize;
            DataTable dtClone = dt.Clone() ;
            for (int i = startIndex; i < startIndex + pageSize; i++)
            {
                DataRow drow = dt.Rows[i];
                dtClone.Rows.Add(drow.ItemArray);
                if (dt.Rows.Count <= (i + 1))
                {
                    break;
                }
            }
            dtClone.AcceptChanges();
            return dtClone;
        }

        public string PagationDataClone2Json(object clone,int totalCount)
        {
            string str = "";
            if (clone == null )
            {
                str = "{\"total\":0, \"rows\":[]}";
                return str;
            }

            string o = Newtonsoft.Json.JsonConvert.SerializeObject(clone);
            str = "{\"total\":" + totalCount.ToString() + ", \"rows\":" + o + "}";
            return str;
        }

        public object DataTableFormmater(DataTable dtbl,string formatterJson)
        {
            Dictionary<string, string> settings = null;
            if (!string.IsNullOrEmpty(formatterJson))
            {
                settings = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(formatterJson);
                if (settings.Keys.Count > 0)
                {
                    foreach (string key in settings.Keys)
                    {
                        if (dtbl.Columns.IndexOf(key) == -1)
                        {
                            dtbl.Columns.Add(key, typeof(string));
                        }   
                    }
                }
            }
            dtbl.AcceptChanges();
            List<Dictionary<string, object>> source = new List<Dictionary<string, object>>();
             foreach (DataRow drow in dtbl.Rows)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                foreach (DataColumn dc in dtbl.Columns)
                {
                    string columnName = dc.ColumnName;
                    object value;
                    if (!drow.IsNull(dc))
                    {
                        value = drow[dc];
                        value = PagationCloneAdjustValue(settings, columnName, drow);
                    }
                    else {
                        if (settings!=null && settings.ContainsKey(columnName))
                        {
                            value = PagationCloneAdjustValue(settings, columnName, drow);
                        }
                        else {
                            value = "";
                        }

                        
                    }
                    item[columnName] = value;
                }
                source.Add(item);
            }
            return source;
        }

        private object PagationCloneAdjustValue(Dictionary<string,string> settings,string field,DataRow drow)
        {
            StringHelper strHlp = new StringHelper();
            object _val = "";

            string format = "";
            if (settings != null)
            {
                format = settings.ContainsKey(field) ? settings[field] : "";
            }
            object value = drow[field];
            if (value is DateTime)
            {
                DateTime _date = (DateTime)value;
                if (_date <= DateTime.Parse("1900-01-30"))
                {
                    _val = "";
                }
                else
                {
                    format = string.IsNullOrEmpty(format) ? "{"+ field + ":yyyy-MM-dd}" : format;
                    _val = strHlp.StringFormatByData(format, drow);
                }
            }
            else if (value is decimal)
            {
                format = string.IsNullOrEmpty(format) ? "{"+ field +":F2}" : format;
                _val = strHlp.StringFormatByData(format, drow);
            }
            else if (!string.IsNullOrEmpty(format))
            {
                _val = strHlp.StringFormatByData(format, drow);
            }
            else
            {
                _val = value;
            }
            return _val;
        }

        public string DataSetToJsonStr(DataSet ds, bool isLongTime = false)
        {
            string str = "{";

            foreach (DataTable dt in ds.Tables)
            {
                str += "\"table\"";
                str += this.DataTableToJsonStr(dt);
                str += ",";
            }

            str += "}";

            return str;
        }

        //将DataTable转换成json字符串
        public string DataTableToJsonStr(DataTable dt, bool isLongTime = false)
        {
            return DataTableToJsonStr(dt, -1, -1, isLongTime);
        }

        //将DataTable转换成json字符串
        public string DataTableToJsonStr(DataTable dt, int pageIndex, int pageSize, bool isLongTime = false)
        {
            string str = "";
            int startIndex = 0;

            if (dt == null || dt.Rows.Count <= 0)
            {
                str = "{\"total\":0, \"rows\":[]}";
                return str;
            }

            List<Hashtable> jsone = new List<Hashtable>();
            Hashtable h = new Hashtable();

            if (pageIndex == -1 || pageSize == -1)
            {
                pageIndex = 0;
                pageSize = 100000;
            }

            startIndex = pageIndex * pageSize;

            for (int i = startIndex; i < startIndex + pageSize; i++)
            {
                h = new Hashtable();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string columnName = dt.Columns[j].ColumnName.ToString();
                    object value = dt.Rows[i][columnName];

                    try
                    {
                        if ("DateTime".Equals(dt.Columns[j].DataType.Name))
                        {
                            if (isLongTime)
                                value = ((DateTime)dt.Rows[i][columnName]).ToString("yyyy-MM-dd HH:mm:ss");
                            else
                                value = ((DateTime)dt.Rows[i][columnName]).ToString("yyyy-MM-dd");

                            if (value.ToString().IndexOf("1900-01-01") >= 0)
                                value = "";
                        }
                        else if (dt.Columns[j].DataType == typeof(decimal))
                        {
                            value = string.Format("{0:F2}", ChinaRound(dt.Rows[i][columnName], 2));
                        }
                    }
                    catch (Exception)
                    {
                    }
                    h.Add(columnName, value);
                }
                jsone.Add(h);

                if (dt.Rows.Count <= (i + 1))
                {
                    break;
                }
            }

            string o = Newtonsoft.Json.JsonConvert.SerializeObject(jsone);
            str = "{\"total\":" + dt.Rows.Count + ", \"rows\":" + o + "}";
            return str;
        }

        //将DataTable转换成json字符串
        public string DataTableToJsonStr(DataTable dt, bool isAvg, bool isSum, string footerText, string[] footerColumnName, int pageIndex, int pageSize, bool isLongTime = false)
        {
            string str = "";
            int startIndex = 0;

            if (dt == null)
            {
                str = "{\"total\":0, \"rows\":[],\"footer\":[]}";
                return str;
            }

            if (dt.Rows.Count <= 0)
            {
                str = "{\"total\":0, \"rows\":[],\"footer\":[]}";
                return str;
            }

            List<Hashtable> jsone = new List<Hashtable>();
            Hashtable h = new Hashtable();

            if (pageIndex == -1 || pageSize == -1)
            {
                pageIndex = 0;
                pageSize = 100000;
            }

            startIndex = pageIndex * pageSize;

            for (int i = startIndex; i < startIndex + pageSize; i++)
            {
                h = new Hashtable();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string columnName = dt.Columns[j].ColumnName.ToString();
                    object value = dt.Rows[i][columnName];

                    try
                    {
                        if ("DateTime".Equals(dt.Columns[j].DataType.Name))
                        {
                            if (isLongTime)
                                value = ((DateTime)dt.Rows[i][columnName]).ToString("yyyy-MM-dd HH:mm:ss");
                            else
                                value = ((DateTime)dt.Rows[i][columnName]).ToString("yyyy-MM-dd");

                            if (value.ToString().IndexOf("1900-01-01") >= 0)
                                value = "";
                        }
                        else if (dt.Columns[j].DataType == typeof(decimal))
                        {
                            value = string.Format("{0:F2}", ChinaRound(dt.Rows[i][columnName], 2));
                        }
                    }
                    catch (Exception)
                    {
                    }
                    h.Add(columnName, value);
                }
                jsone.Add(h);

                if (dt.Rows.Count <= (i + 1))
                {
                    break;
                }
            }

            string avgJson = "";
            string sumJson = "";
            string joinString = "";
            if (isAvg && dt.Rows.Count > 0)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (string col in footerColumnName)
                {
                    dic[col] = string.Format("{0:F}", dt.Compute(string.Format("AVG([{0:f2}])", col), "")); ;
                }
                dic[footerText] = "平均值:";
                avgJson = JavaScriptConvertMachion(dic);
                joinString = avgJson;
            }

            if (isSum && dt.Rows.Count > 0)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (string col in footerColumnName)
                {
                    dic[col] = string.Format("{0:F}", dt.Compute(string.Format("SUM([{0}])", col), ""));
                }
                dic[footerText] = "<span  style=\" float:right\">合计:</span>";
                sumJson = JavaScriptConvertMachion(dic);
                if (!string.IsNullOrEmpty(joinString))
                {
                    joinString += ",";
                }
                joinString += sumJson;
            }

            if (!string.IsNullOrEmpty(joinString))
            {
                joinString = ",\"footer\":[" + joinString + "]";
            }

            string o = Newtonsoft.Json.JsonConvert.SerializeObject(jsone);
            str = "{\"total\":" + dt.Rows.Count + ", \"rows\":" + o + joinString + "}";
            return str;
        }

        private void WriteTab(StringBuilder strSrc, int tabNum)
        {
            strSrc.AppendLine("");
            for (int i = 0; i < tabNum; ++i)
                strSrc.Append("\t");
        }

        private void WriteJsonStr(StringBuilder strSrc, string strValueField, string strTextField, int tabNum)
        {
            WriteTab(strSrc, tabNum);
            strSrc.Append("	\"" + strValueField + "\":\"" + strTextField + "\"");
        }

        private void WriteJsonInt(StringBuilder strSrc, string strValueField, string strTextField, int tabNum)
        {
            WriteTab(strSrc, tabNum);
            strSrc.Append("	\"" + strValueField + "\":" + strTextField);
        }

        private List<Hashtable> FindDataRow(DataTable dt, int rowIndex)
        {
            List<Hashtable> rowList = new List<Hashtable>();
            Hashtable h = new Hashtable();
            string columnName = "";
            string value = "";
            if (dt.Rows.Count > rowIndex)
            {
                for (int i = 0; i < dt.Columns.Count; ++i)
                {
                    columnName = dt.Columns[i].ColumnName.ToString();
                    value = dt.Rows[rowIndex][columnName].ToString();
                    try
                    {
                        if ("DateTime".Equals(dt.Columns[i].DataType.Name))
                        {
                            value = dt.Rows[i][columnName].ToString();
                            value = Convert.ToDateTime(value).ToString("yyyy-MM-dd");
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    h.Add(columnName, value);
                    h.Add(i, columnName);
                }
                rowList.Add(h);
            }
            return rowList;
        }

        private bool CheckIsChild(ListTree fatherList, ListTree childList, string fatherColName, string childColName)
        {
            if (childList.list[0][childColName].Equals(fatherList.list[0][fatherColName]))
            {
                return true;
            }
            return false;
        }

        private bool CheckIsBrother(ListTree fatherList, ListTree brotherList, string brotherColName)
        {
            if (brotherList.list[0][brotherColName].Equals(fatherList.list[0][brotherColName]))
            {
                return true;
            }
            return false;
        }

        private bool FindAndSetList(ListTree head, ListTree temp, string fatherColName, string childColName)
        {
            ListTree lastTemp = head;
            if (CheckIsBrother(head, temp, childColName))
            {
                while (head.brother != null)
                {
                    lastTemp = head;
                    head = head.brother;
                }
                head.brother = temp;
                if (lastTemp.father != null)
                {
                    head.brother.father = lastTemp.father;
                }

                return true;
            }
            else
            {
                if (CheckIsChild(head, temp, fatherColName, childColName))
                {
                    if (head.child == null)
                    {
                        head.child = temp;
                        head.child.father = head;
                    }
                    else
                    {
                        lastTemp = head;
                        head = head.child;
                        while (head.brother != null)
                        {
                            head = head.brother;
                        }
                        head.brother = temp;
                        head.brother.father = lastTemp;
                    }
                    return true;
                }
            }

            return false;
        }

        private bool SetListTree(ListTree head, DataTable dt, int childIndex, string fatherColName, string childColName)
        {
            ListTree temp = new ListTree();
            ListTree tempHead = head;

            temp.list = FindDataRow(dt, childIndex);

            if (EachBorther(head, temp, fatherColName, childColName))
            {
                return true;
            }

            return false;
        }

        private bool SetListTree(ListTree head, List<Hashtable> lt, string fatherColName, string childColName)
        {
            ListTree temp = new ListTree();
            ListTree tempHead = head;

            temp.list = lt;

            if (EachBorther(head, temp, fatherColName, childColName))
            {
                return true;
            }

            return false;
        }

        private bool EachChild(ListTree head, ListTree temp, string fatherColName, string childColName)
        {
            while (head != null)
            {
                if (FindAndSetList(head, temp, fatherColName, childColName))
                {
                    return true;
                }

                if (EachBorther(head.brother, temp, fatherColName, childColName))
                {
                    return true;
                }

                head = head.child;
            }

            return false;
        }

        private bool EachBorther(ListTree head, ListTree temp, string fatherColName, string childColName)
        {
            while (head != null)
            {
                if (FindAndSetList(head, temp, fatherColName, childColName))
                {
                    return true;
                }

                if (EachChild(head.child, temp, fatherColName, childColName))
                {
                    return true;
                }

                head = head.brother;
            }

            return false;
        }

        private ListTree InitListTree(DataTable dt, string fatherColName, string childColName)
        {
            int index = 0;
            ListTree head = new ListTree();
            ArrayList myList = new ArrayList();
            head.list = FindDataRow(dt, index);
            for (int i = 1; i < dt.Rows.Count; ++i)
            {
                if (!SetListTree(head, dt, i, fatherColName, childColName))
                {
                    myList.Add(FindDataRow(dt, i));
                }
            }

            for (int i = 0; i < myList.Count; ++i)
            {
                SetListTree(head, (List<Hashtable>)myList[i], fatherColName, childColName);
            }
            return head;
        }

        private int WriteJsonForListTree(ListTree head, StringBuilder strResult)
        {
            int count = 0;
            int tabNum = 1;
            string colName = "";
            ListTree tempHead = head;
            ListTree LastBorther = null;
            strResult.AppendLine("[{");

            while (head != null)
            {
                for (int i = 0; i < head.list[0].Count / 2 - 1; ++i)
                {
                    colName = head.list[0][i].ToString();
                    try
                    {
                        Convert.ToInt32(head.list[0][colName]);
                        if (colName.Equals("checked"))
                        {
                            if (head.child != null)
                            {
                                WriteJsonInt(strResult, colName, "0", tabNum);
                            }
                            else
                            {
                                WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                            }
                        }
                        else
                        {
                            WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (head.child == null && colName.Equals("state"))
                        {
                            head.list[0][colName] = "";
                        }
                        WriteJsonStr(strResult, colName, head.list[0][colName].ToString(), tabNum);
                    }
                    strResult.Append(",");
                }
                colName = head.list[0][head.list[0].Count / 2 - 1].ToString();
                try
                {
                    Convert.ToInt32(head.list[0][colName]);
                    if (colName.Equals("checked"))
                    {
                        if (head.child != null)
                        {
                            WriteJsonInt(strResult, colName, "0", tabNum);
                        }
                        else
                        {
                            WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                        }
                    }
                    else
                    {
                        WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                    }
                }
                catch (Exception ex)
                {
                    if (head.child == null && colName.Equals("state"))
                    {
                        head.list[0][colName] = "";
                    }
                    WriteJsonStr(strResult, colName, head.list[0][colName].ToString(), tabNum);
                }
                count++;
                if (head.child != null)
                {
                    head = head.child;
                    ++tabNum;
                    WriteTab(strResult, tabNum);
                    strResult.Append(",\"children\":[{");
                }
                else
                {
                    LastBorther = head;
                    head = head.brother;

                    if (head != null)
                    {
                        WriteTab(strResult, tabNum);
                        strResult.Append("},{");
                    }
                    else
                    {
                        if (LastBorther.father != null)
                        {
                            head = LastBorther.father;
                            WriteTab(strResult, tabNum--);
                            strResult.Append("}]");

                            while (head.brother == null)
                            {
                                WriteTab(strResult, tabNum--);
                                strResult.Append("}]");
                                head = head.father;
                                if (head == null)
                                {
                                    break;
                                }
                            }
                            if (head != null)
                            {
                                head = head.brother;
                            }
                        }

                        if (head != null)
                        {
                            WriteTab(strResult, tabNum);
                            strResult.Append("},{");
                        }
                    }
                }
            }
            for (; tabNum > 0; --tabNum)
            {
                WriteTab(strResult, tabNum);
                strResult.Append("}]");
            }

            return count;
        }

        private int WriteJsonForListTree(ListTree head, StringBuilder strResult, string strChildName)
        {
            int count = 0;
            int tabNum = 1;
            string colName = "";
            ListTree tempHead = head;
            ListTree LastBorther = null;

            //strResult.AppendLine("{").Append("\t" + strChildName).Append(":[{");
            strResult.Append("[{");

            while (head != null)
            {
                for (int i = 0; i < head.list[0].Count / 2 - 1; ++i)
                {
                    colName = head.list[0][i].ToString();
                    try
                    {
                        Convert.ToInt32(head.list[0][colName]);
                        WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                    }
                    catch (Exception ex)
                    {
                        WriteJsonStr(strResult, colName, head.list[0][colName].ToString(), tabNum);
                    }
                    strResult.Append(",");
                }
                colName = head.list[0][head.list[0].Count / 2 - 1].ToString();
                try
                {
                    Convert.ToInt32(head.list[0][colName]);
                    WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                }
                catch (Exception ex)
                {
                    WriteJsonStr(strResult, colName, head.list[0][colName].ToString(), tabNum);
                }
                count++;
                if (head.child != null)
                {
                    head = head.child;
                    ++tabNum;
                    WriteTab(strResult, tabNum);
                    strResult.Append(",").Append(strChildName).Append(":[{");
                }
                else
                {
                    LastBorther = head;
                    head = head.brother;

                    if (head != null)
                    {
                        WriteTab(strResult, tabNum);
                        strResult.Append("},{");
                    }
                    else
                    {
                        if (LastBorther.father != null)
                        {
                            head = LastBorther.father;
                            WriteTab(strResult, tabNum--);
                            strResult.Append("}]");

                            while (head.brother == null)
                            {
                                WriteTab(strResult, tabNum--);
                                strResult.Append("}]");
                                head = head.father;
                                if (head == null)
                                {
                                    break;
                                }
                            }
                            if (head != null)
                            {
                                head = head.brother;
                            }
                        }

                        if (head != null)
                        {
                            WriteTab(strResult, tabNum);
                            strResult.Append("},{");
                        }
                    }
                }
            }
            for (; tabNum > 0; --tabNum)
            {
                WriteTab(strResult, tabNum);
                strResult.Append("}]");
            }
            WriteTab(strResult, tabNum);
            //strResult.Append("}");

            return count;
        }

        private int WriteJsonForListTreeCheckedFather(ListTree head, StringBuilder strResult)
        {
            int count = 0;
            int tabNum = 1;
            string colName = "";
            ListTree tempHead = head;
            ListTree LastBorther = null;
            strResult.AppendLine("[{");

            while (head != null)
            {
                for (int i = 0; i < head.list[0].Count / 2 - 1; ++i)
                {
                    colName = head.list[0][i].ToString();
                    try
                    {
                        Convert.ToInt32(head.list[0][colName]);
                        WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                    }
                    catch (Exception ex)
                    {
                        if (head.child == null && colName.Equals("state"))
                        {
                            head.list[0][colName] = "";
                        }
                        WriteJsonStr(strResult, colName, head.list[0][colName].ToString(), tabNum);
                    }
                    strResult.Append(",");
                }
                colName = head.list[0][head.list[0].Count / 2 - 1].ToString();
                try
                {
                    Convert.ToInt32(head.list[0][colName]);
                    WriteJsonInt(strResult, colName, head.list[0][colName].ToString(), tabNum);
                }
                catch (Exception ex)
                {
                    if (head.child == null && colName.Equals("state"))
                    {
                        head.list[0][colName] = "";
                    }
                    WriteJsonStr(strResult, colName, head.list[0][colName].ToString(), tabNum);
                }
                count++;
                if (head.child != null)
                {
                    head = head.child;
                    ++tabNum;
                    WriteTab(strResult, tabNum);
                    strResult.Append(",\"children\":[{");
                }
                else
                {
                    LastBorther = head;
                    head = head.brother;

                    if (head != null)
                    {
                        WriteTab(strResult, tabNum);
                        strResult.Append("},{");
                    }
                    else
                    {
                        if (LastBorther.father != null)
                        {
                            head = LastBorther.father;
                            WriteTab(strResult, tabNum--);
                            strResult.Append("}]");

                            while (head.brother == null)
                            {
                                WriteTab(strResult, tabNum--);
                                strResult.Append("}]");
                                head = head.father;
                                if (head == null)
                                {
                                    break;
                                }
                            }
                            if (head != null)
                            {
                                head = head.brother;
                            }
                        }

                        if (head != null)
                        {
                            WriteTab(strResult, tabNum);
                            strResult.Append("},{");
                        }
                    }
                }
            }
            for (; tabNum > 0; --tabNum)
            {
                WriteTab(strResult, tabNum);
                strResult.Append("}]");
            }

            return count;
        }

        public string DataTableMenuToJson(DataTable dt, string fatherColName, string childColName, string title)
        {
            return JSONHelper.Instance.JavaScriptConvertMachion(EachDataTable(dt, fatherColName, childColName, title, "0"));
        }

        public List<Dictionary<string, object>> EachDataTable(DataTable dt, string fatherColName, string childColName, string title, string DefaultValue)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            Dictionary<string, object> dic = null;

            foreach (DataRow dr in dt.Select(string.Format(" {0} = {1} ", childColName, DefaultValue)))
            {
                dic = new Dictionary<string, object>();

                foreach (DataColumn dc in dt.Columns)
                {
                    dic[dc.ColumnName] = dr[dc.ColumnName];
                }
                List<Dictionary<string, object>> listChild = EachDataTable(dt, fatherColName, childColName, title, dr[fatherColName].ToString());
                dic[title] = listChild;
                list.Add(dic);
            }

            return list;
        }

        public string DataTableMenuToJsonStrNoTotal(DataTable dt, string fatherColName, string childColName)
        {
            StringBuilder result = new StringBuilder();
            if (dt.Rows.Count <= 0)
            {
                return result.ToString();
            }

            ListTree head = InitListTree(dt, fatherColName, childColName);
            WriteJsonForListTree(head, result, "\"SUB_MENU\"");

            return result.ToString();
        }

        public string DataTableTreeToJsonStrCheckedFather(DataTable dt, string fatherColName, string childColName)
        {
            StringBuilder result = new StringBuilder();
            if (dt.Rows.Count <= 0)
            {
                return result.ToString();
            }

            ListTree head = InitListTree(dt, fatherColName, childColName);
            WriteJsonForListTreeCheckedFather(head, result);

            return result.ToString();
        }

        public string DataTableTreeToJsonStrNoTotal(DataTable dt, string fatherColName, string childColName)
        {
            StringBuilder result = new StringBuilder();

            if (dt.Rows.Count <= 0)
            {
                return "[]";
            }

            ListTree head = InitListTree(dt, fatherColName, childColName);
            WriteJsonForListTree(head, result);

            return result.ToString();
        }

        public string DataTableToJsonStrNoTotal(DataTable dt, bool isLongTime = false)
        {
            string str = "[]";
            int startIndex = 0;

            if (dt.Rows.Count <= 0)
            {
                return str;
            }

            List<Hashtable> jsone = new List<Hashtable>();
            Hashtable h = new Hashtable();

            for (int i = startIndex; i < dt.Rows.Count; i++)
            {
                h = new Hashtable();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string columnName = dt.Columns[j].ColumnName.ToString();
                    string value = dt.Rows[i][columnName].ToString();
                    try
                    {
                        if ("DateTime".Equals(dt.Columns[j].DataType.Name))
                        {
                            value = dt.Rows[i][columnName].ToString();
                            if (isLongTime)
                            {
                                value = ((DateTime)dt.Rows[i][columnName]).ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            else
                            {
                                value = Convert.ToDateTime(value).ToString("yyyy-MM-dd");
                            }

                            if (value.ToString().IndexOf("1900-01-01") >= 0)
                            {
                                value = "";
                            }
                        }
                        else if (dt.Columns[j].DataType == typeof(decimal))
                        {
                            value = string.Format("{0:F2}", ChinaRound(dt.Rows[i][columnName], 2));
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    h.Add(columnName, value);
                }
                jsone.Add(h);
            }
            return JsonConvert.SerializeObject(jsone);
            //return JavaScriptConvert.SerializeObject(jsone);
        }

        public string DataTableToJsonTree(DataTable dt)
        {
            StringBuilder str = new StringBuilder();
            str.Append("[]");
            if (dt == null)
                return str.ToString();

            if (dt.Rows.Count <= 0)
                return str.ToString();

            str = new StringBuilder();

            DataTable dtAttributes = dt.Copy();
            DataTable dtTree = dt.Copy();
            string[] delColNames = new string[] { "id", "text", "checked", "state", "iconCls" };

            foreach (string delColName in delColNames)
            {
                if (dtAttributes.Columns.Contains(delColName))
                    dtAttributes.Columns.Remove(delColName);
            }

            foreach (DataColumn dc in dtAttributes.Columns)
            {
                dtTree.Columns.Remove(dc.ColumnName);
            }

            str.Append("[");
            foreach (DataRow dr in dt.Rows)
            {
                str.Append("{");
                foreach (DataColumn dc in dtTree.Columns)
                {
                    string columnName = dc.ColumnName;
                    string value = dr[columnName].ToString();
                    try
                    {
                        if ("DateTime".Equals(dc.DataType.Name))
                        {
                            value = Convert.ToDateTime(value).ToString("yyyy-MM-dd");
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    WriteJsonStr(str, columnName, value, 1);
                    str.Append(",");
                }
                str.Append("\"attributes\":{");

                foreach (DataColumn dc in dtAttributes.Columns)
                {
                    string columnName = dc.ColumnName;
                    string value = dr[columnName].ToString();
                    try
                    {
                        if ("DateTime".Equals(dc.DataType.Name))
                        {
                            value = Convert.ToDateTime(value).ToString("yyyy-MM-dd");
                        }
                    }
                    catch (Exception)
                    {
                    }
                    WriteJsonStr(str, columnName, value, 2);
                    str.Append(",");
                }
                if (dtAttributes.Columns.Count > 0)
                    str.Remove(str.Length - 1, 1);

                str.Append("}");
                str.Append("},");
            }
            str.Remove(str.Length - 1, 1);
            str.Append("]");

            return str.ToString();
        }

        public delegate EasyuiTreeNodeEntity[] delegateJsonTreeByRecursion(DataTable dtbData);

        public delegate EasyuiTreeNodeEntity[] delegateJsonTreeByRecursion_Sub(DataTable dtbData, EasyuiTreeNodeEntity parent);

        public EasyuiTreeNodeEntity[] DataTableToJsonTreeByRecursion(DataTable dtblData,
                                                            delegateJsonTreeByRecursion funcByRecursion,
                                                        delegateJsonTreeByRecursion_Sub funcByRecursion_Sub
                                                                                                )
        {
            List<EasyuiTreeNodeEntity> roots = new List<EasyuiTreeNodeEntity>(funcByRecursion(dtblData));
            foreach (EasyuiTreeNodeEntity node in roots)
            {
                DataTableToJsonTreeByRecursion_Sub(dtblData, node, funcByRecursion_Sub);
            }
            return roots.ToArray();
        }

        private void DataTableToJsonTreeByRecursion_Sub(DataTable dtblData, EasyuiTreeNodeEntity parent, delegateJsonTreeByRecursion_Sub funcByRecursion_Sub)
        {
            List<EasyuiTreeNodeEntity> nodes = new List<EasyuiTreeNodeEntity>(funcByRecursion_Sub(dtblData, parent));
            parent.children = nodes;
            if (nodes.Count == 0)
            {
                parent.state = "open";
                return;
            }

            foreach (EasyuiTreeNodeEntity node in nodes)
            {
                DataTableToJsonTreeByRecursion_Sub(dtblData, node, funcByRecursion_Sub);
            }
        }

        #region FormatReplyJson

        /// <summary>
        /// 过滤Json非法字符
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private static string encodeJSON(string result)
        {
            result = result.Replace("\'", "");
            result = result.Replace('[', ' ');
            result = result.Replace(']', ' ');
            result = result.Replace('{', ' ');
            result = result.Replace('}', ' ');
            result = result.Replace(':', ' ');
            result = result.Replace(',', ' ');
            return result;
        }

        /// <summary>
        /// 生成JSON格式输出
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="result"></param>
        /// <param name="isEncode"></param>
        /// <returns></returns>
        public static string formatReplyJson(bool isSuccess, string result, bool isEncode)
        {
            string _success = isSuccess ? "true" : "false";
            if (isEncode)
            {
                result = encodeJSON(result);
                result = "\"" + result + "\"";
            }

            return "{" + string.Format("\"success\":{0},\"result\":{1}", _success, result) + "}";
        }

        /// <summary>
        /// 生成JSON格式输出
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="result"></param>
        /// <param name="isEncode"></param>
        /// <returns></returns>
        public static string formatReplyJson(IDictionary<string, object> outputParams, bool isEncode)
        {
            if (outputParams == null)
                return "[]";

            string result = "";
            try
            {
                if (isEncode)
                {
                    string key = "";
                    string value = "";
                    result = "[";

                    result += "{";
                    foreach (KeyValuePair<string, object> item in outputParams)
                    {
                        key = item.Key;
                        key = "\"" + key + "\"";

                        value = item.Value.ToString();

                        if (item.Value is DateTime)
                        {
                            value = string.Format("yyyy-MM-dd HH:mm:ss", item.Value);

                            if (value.ToString().IndexOf("1900-01-01") >= 0)
                            {
                                value = "";
                            }
                        }
                        else if (item.Value is decimal)
                        {
                            value = string.Format("{0:F2}", ChinaRound(item.Value, 2));
                        }
                        else
                        {
                            value = item.Value.ToString();
                        }

                        // value = encodeJSON(value);
                        value = "\"" + value + "\"";

                        result += key + ":" + value + ",";
                    }
                    result = result.Substring(0, result.Length - 1);
                    result += "}";
                    result += "]";
                }
            }
            catch
            {
                return "[]";
            }

            return result;
        }

        /// <summary>
        /// 生成JSON格式输出,无result property
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="result"></param>
        /// <param name="isEncode"></param>
        /// <returns></returns>
        public static string formatReplyJsonNoResult(bool isSuccess, string result, bool isEncode)
        {
            string _success = isSuccess ? "0" : "99";
            if (isEncode)
            {
                result = encodeJSON(result);
            }

            return "{" + string.Format("\"RETURN_CODE\":{0},\"RETURN_MESSAGE\":\"{1}\"", _success, result) + "}";
        }

        #endregion FormatReplyJson

        //四舍五入方法
        private static object ChinaRound(object v, int decimals)
        {
            if (v is double)
            {
                double value = (double)v;
                if (value < 0)
                {
                    return Math.Round(value + 5 / Math.Pow(10, decimals + 1), decimals, MidpointRounding.AwayFromZero);
                }
                else
                {
                    return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
                }
            }
            else if (v is decimal)
            {
                decimal value1 = (decimal)v;
                if (value1 < 0)
                {
                    return Math.Round(value1 + Convert.ToDecimal(5 / Math.Pow(10, decimals + 1)), decimals, MidpointRounding.AwayFromZero);
                }
                else
                {
                    return Math.Round(value1, decimals, MidpointRounding.AwayFromZero);
                }
            }
            return 0.0;
        }

        /// <summary>
        /// 生成JSON树
        /// </summary>
        /// <returns></returns>
        public string DataSetToJsonStr(DataSet ds)
        {
            List<Dictionary<string, object>> jsonList = new List<Dictionary<string, object>>();
            Dictionary<string, object> jsonDictionary = null;

            Dictionary<string, object> jsonDetailDictionary = null;

            if (ds.Tables.Count > 1)
            {
                DataTable dt = ds.Tables[1];
                List<Dictionary<string, object>> jsonDetailList = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    jsonDetailDictionary = new Dictionary<string, object>();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        jsonDetailDictionary[dc.ColumnName] = dr[dc.ColumnName];
                    }
                    jsonDetailList.Add(jsonDetailDictionary);
                }

                dt = ds.Tables[0];
                jsonDictionary = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    jsonDictionary[dc.ColumnName] = ds.Tables[0].Rows[0][dc.ColumnName];
                }

                jsonDictionary["children"] = jsonDetailList;
                jsonList.Add(jsonDictionary);
            }
            return JsonConvert.SerializeObject(jsonList);
        }

        /// <summary>
        /// 生成JSON树
        /// </summary>
        /// <returns></returns>
        public string DataSetToJsonStra(DataSet ds)
        {
            string json = "";
            IList<Hashtable> mList = new List<Hashtable>();

            try
            {
                if (ds.Tables.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        Hashtable ht = new Hashtable();
                        foreach (DataColumn col in ds.Tables[0].Columns)
                        {
                            string _v = "";
                            if (col.DataType.Equals(typeof(DateTime)))
                            {
                                _v = string.Format("{0:yyyy-MM-dd HH:mm:ss}", row[col.ColumnName]);
                            }
                            else
                            {
                                _v = row[col.ColumnName].ToString();
                            }

                            ht.Add(col.ColumnName, _v);
                        }
                        mList.Add(ht);
                    }
                }

                json = JsonConvert.SerializeObject(mList);
            }
            catch (Exception ee)
            {
                string error = ee.Message;
            }
            return json;
        }
    }
}